package com.itzhouwei.commerce.nacos;
/*
 * @作者 伟子涵
 * @微信公号 搬砖暗夜码农
 * @开源项目 $ https://gitee.com/zhouwei5208888
 * @我的博客 $ http://itzhouwei.com
 * @创建时间 2024/1/8  10:42
 */



import com.alibaba.nacos.common.codec.Base64;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;

/**
 * @description:
 * @author：zw，微信：yingshengzw
 * @date: 2024/1/8  10:42
 * @Copyright： 公众号：搬砖暗夜码农 | 博客：https://itzhouwei.com - 沉淀、分享、成长，让自己和他人都能有所收获！
 *
 *
 * 在配置文件当中 需要配置
 * ## 钉钉机器人
 * #dingtalk:
 * #  webhook: https://oapi.dingtalk.com/robot/send?access_token=3052b473d3531d327642c598dab7c09c80ba6265de1812f464ba6c51900b39e76
 * #  secret: xxx
 *
 * spring:
 *   application:
 *     name: fulimall-crm-server
 *
 *   profiles:
 *     active: dev
 *
 *
 */
@Slf4j
public class DingTalkUtil {


    public static void sendMsg(SendMessage msg) {
        try {
            Long timestamp = System.currentTimeMillis();
            String secret = msg.getSecret();

            String stringToSign = timestamp + "\n" + secret;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");


            DingTalkClient client = new DefaultDingTalkClient(msg.getWebhook() + "&timestamp=" + timestamp + "&sign=" + sign);
            OapiRobotSendRequest request = new OapiRobotSendRequest();

            OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
            //推送所有人
            at.setIsAtAll(true);
            request.setAt(at);

            //文本消息
            request.setMsgtype("text");
            OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
            text.setContent("错误信息"+msg.getText());
            request.setText(text);

            OapiRobotSendResponse response = client.execute(request);
            log.info("钉钉推送返回结果：" + response);
        } catch (Exception e) {
            log.error("钉钉通知异常", e);
        }
    }

}
